/* eslint-disable max-lines */
/* eslint-disable react/jsx-closing-tag-location */
import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import { Button, Dialog, Form, DatePicker2 } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid, TitleGrid, orderModel, column, DATETIME_TEXT } from '../stores/definitions.js';
import { observer } from 'mobx-react-lite';
import { toJS, observable } from 'mobx';
import moment from 'moment';

const FromItem = Form.Item;

function Change({ orderId, modal, onSubmit, onCancel }) {
  const { scOrderStore: store } = useStore();
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [change] = useState(() => observable({}));

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      if (orderId) {
        const res = await store.get(orderId);
        editCtx.origin = _.cloneDeep(res);
        _.assign(change, res);
      }
    })();
    return () => {
      store._changeStatus = '0';
    };
  }, []);

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(change, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const overrideModel = {
    scOrder: {
      passengerName: {
        ui: {
          itemProps: {
            required: true,
          },
        },
      },
      passengerPhone: {
        ui: {
          itemProps: {
            format: 'tel',
            required: true,
          },
        },
      },
      shiftTime: {
        ui: {
          renderer: (v) => (
            <DatePicker2
              value={v}
              format="YYYY-MM-DD HH:mm"
              showTime
              outputFormat={'YYYY-MM-DD HH:mm'}
              timePanelProps={{ format: 'HH:mm' }}
            />
          ),
        },
      },
    },
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign, no-param-reassign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  // 提交
  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: OrderChange.jsx:90 _ errors:', errors);
      return;
    }
    const {
      id,
      remark,
      scOrder,
    } = change;
    const data = {
      orderId: id,
      name: scOrder?.passengerName,
      phone: scOrder?.passengerPhone,
      shiftDate: moment.utc(scOrder?.shiftTime).subtract(8, 'hour').toISOString(),
      remark,
    };
    onSubmit?.(data);
  };

  return (
    <Form
      inline
      value={change}
      onChange={handleChange}
      useLabelForErrorMessage
      isPreview
    >
      <TitleGrid title={t`下单信息`} />
      <FieldsGrid
        formData={change}
        mode={'view'}
        overrideModel={overrideModel}
        columns={4}
        fields={['subscribeName', 'subscribePhone']
          .map((p) => `scOrder.${p}`).concat(['beginAreaName', 'endAreaName'])}
      />
      <br />
      <FieldsGrid
        formData={change}
        overrideModel={overrideModel}
        columns={4}
        fields={['passengerName', 'passengerPhone', 'shiftTime']
          .map((p) => `scOrder.${p}`)}
      />
      <TitleGrid title={t`其他信息`} />
      <FieldsGrid
        formData={change}
        mode={'edit'}
        overrideModel={overrideModel}
        columns={4}
        fields={['remark']}
      />
      <DrawerFooter>
        <FromItem>
          <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
}

export default observer(Change);

